<template>
  <div>
    <a-modal
      :title="title"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
      :width="800"
      destroyOnClose
    >
      <a-alert
        message="只有订单未付款时才支持改价，改价后请联系买家刷新订单核实订单金额后再支付。"
        banner
      />
      <a-table
        :columns="columns"
        :data-source="data"
        bordered
        :loading="confirmLoading"
        style="margin-top: 20px"
      >
        <template slot="modifyPrice" slot-scope="text, record">
          <a-input-number
            :max="100000"
            :formatter="
              (value) => {
                let reg = /^(-)*(\d+)\.(\d\d).*$/;
                return `${value}`
                  .replace(/\B(?=(\d{6})+(?!\d))/g, ',')
                  .replace(reg, '$1$2.$3');
              }
            "
            v-model="record.modifyPrice"
            :default-value="0.0"
          />
        </template>
        <template slot="freight" slot-scope="text, record">
          <a-input-number
            :min="0.0"
            :max="10000"
            :formatter="
              (value) => {
                let reg = /^(-)*(\d+)\.(\d\d).*$/;
                return `${value}`
                  .replace(/\B(?=(\d{6})+(?!\d))/g, ',')
                  .replace(reg, '$1$2.$3');
              }
            "
            v-model="record.freight"
            :default-value="0.0"
          />
        </template>

        <template slot="freight" slot-scope="text, record">
          <a-input-number
            :min="0.0"
            :max="10000"
            :formatter="
              (value) => {
                let reg = /^(-)*(\d+)\.(\d\d).*$/;
                return `${value}`
                  .replace(/\B(?=(\d{6})+(?!\d))/g, ',')
                  .replace(reg, '$1$2.$3');
              }
            "
            v-model="record.freight"
            :default-value="0.0"
          />
        </template>
      </a-table>
      <div>
        <p>当有多个商品时，建议你合理分配订单改价金额，确保与顾客已协商一致</p>
        <p>
          收货地址：{{ records.provinceName }} {{ records.cityName }}
          {{ records.districtName }} {{ records.detailAddress }}
        </p>
        <p>实付金额 = 小计+店铺优惠+小计涨减价+运费</p>
        <p>
          店铺优惠金额会均摊到每个商品中，商品小计加上店铺优惠和小计改价金额后不能小于0
        </p>
      </div>
    </a-modal>
  </div>
</template>
<script>
export default {
  data() {
    return {
      visible: false,
      confirmLoading: false,
      fileList: [],
      express: "",
      courierNumber: [{ value: "" }],
      formData: {
        express: "",
        courierNumber: [],
      },
      isAllowUpdate:false,
      data: [],
      columns: [
        {
          title: "商品",
          dataIndex: "goodsName",
          align: "center",
          key: "goodsName",
        },
        {
          title: "单价（元）",
          dataIndex: "goodsPrice",
          key: "goodsPrice",
          customRender: (value) => {
            if (!value) return "0.00";
            return `${(value / 100).toFixed(2)}`;
          },
        },
        {
          title: "数量",
          dataIndex: "goodsNum",
          key: "goodsNum",
        },
        {
          title: "小计（元）",
          dataIndex: "goodsOrderPrice",
          customRender: (value) => {
            if (!value) return "0.00";
            return `${(value / 100).toFixed(2)}`;
          },
        },
        {
          title: "优惠",
          dataIndex: "couponAmount",
          customRender: (value) => {
            if (!value) return "0.00";
            return `${(value / 100).toFixed(2)}`;
          },
        },
        {
          title: "涨价或减价",
          dataIndex: "modifyPrice",
          scopedSlots: { customRender: "modifyPrice" },
        },
        {
          title: "运费（元）",
          dataIndex: "freight",
          scopedSlots: { customRender: "freight" },
        },
        {
          title: "实际金额",
          dataIndex: "toatl",
          customRender: (value, record) => {
            let goodsOrderPrice = +record.goodsOrderPrice;
            let modifyPrice = record.modifyPrice ? record.modifyPrice : 0;
            let freight = record.freight ? record.freight : 0;
            let couponAmount = record.couponAmount ? record.couponAmount : 0;
            let price = (
              (goodsOrderPrice +
                Math.round(modifyPrice * 10 * 10) +
                Math.round(freight * 10 * 10) -
                +couponAmount) /
              100
            ).toFixed(2);
            this.isAllowUpdate=!!(price>=0);
            // if(!(typeof price === 'number' && !isNaN(price))){
            //   alert(1)
            //   this.isAllowUpdate=false;
            // }
            return price;
          },
        },
      ],
    };
  },
  props: {
    value: {
      require: true,
      default: false,
      type: Boolean,
    },
    title: {
      default: "发货信息",
      type: String,
    },
    records: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  mounted() {
    // this.form = this.$form.createForm(this, { name: "coordinated" });
  },

  filters: {
    filterPrice(value) {
      if (!value) return "0.00";
      return `${(value / 100).toFixed(2)}`;
    },
  },
  watch: {
    value(val) {
      console.log(val);
      this.visible = val;
    },
    visible(val) {
      if (val && this.records.id) {
        this.$nextTick(() => {
          console.log(this.records);
          let obj = JSON.parse(JSON.stringify(this.records));
          this.data = [obj];
        });
      }
      this.$emit("input", val);
    },
  },
  methods: {
    addCourierNumber() {
      let list = {
        value: "",
      };
      this.courierNumber.push(list);
    },
    showModal() {
      this.visible = true;
    },
    handleOk(e) {
      if(!this.isAllowUpdate){
        this.$message.error('实际金额不能小于0');
        return;
      }
      this.confirmLoading = true;
      console.log(this.data, "data");
      let obj = this.data[0];
      let url = "/order/goods/update/price";
      let parmas = {
        orderGoodsId: obj.id,
        change: obj.modifyPrice < 0 ? 2 : 1,
        changePrice: Math.round(obj.modifyPrice * 10 * 10),
        freightPrice: Math.round(obj.freight * 10 * 10),
        orderPrice:
          +obj.goodsOrderPrice + Math.round(obj.modifyPrice * 10 * 10) + +obj.couponAmount,
      };
      this.$post(url, { ...parmas }).then((res) => {
        if (res && res.returnCode === 1000) {
          this.$message.success("改价成功！");
          this.$emit("handleSubmit");
        }
      });
      this.confirmLoading = false;
    },
    handleCancel(e) {
      this.visible = false;
    },
    handleChange(info) {
      this.fileList = [info];
    },
  },
};
</script>
